﻿using MongoDB.Bson;
using MongoDB.Driver;
using SupermarkedModel;
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.IO;
using System.Linq;


//CREATE PROC usp_FindIncome (@productId int) 
//AS
//	SELECT SUM(r.Sum) 
//	FROM Reports r
//	INNER JOIN Products p
//	ON r.ProductID = p.ID
//	WHERE p.ID = @productId
//GO

//CREATE PROC usp_FindQuantity (@productId int) 
//AS
//	SELECT SUM(r.Quantity) 
//	FROM Reports r
//	INNER JOIN Products p
//	ON r.ProductID = p.ID
//	WHERE p.ID = @productId
//GO

namespace Supermarket.Client
{
    internal static class JsonGenerator
    {

        public static void RecordJsonFilesAndMongo()
        {
            //List<JObject> list = GenerateJSons();

            Dictionary<int, string> resultingJsons = GenerateJSons();
            RecordInMongoDB(resultingJsons);
            RecordFiles(resultingJsons);
        }

        public static Dictionary<int, string> GenerateJSons() //List<JObject>
        {
            SupermarketDbEntities entities = new SupermarketDbEntities();

            // List<JObject> jsonObjects = new List<JObject>();
            Dictionary<int, string> resultJsons = new Dictionary<int, string>();
            using (entities)
            {
                foreach (var product in entities.Products)
                {
                    int productId = product.ID;
                    string productName = product.ProductName;
                    string vendorName = product.Vendor.VendorName;

                    ObjectResult<decimal?> incomeCollection = entities.usp_FindIncome(product.ID);
                    decimal? productIncome = incomeCollection.FirstOrDefault();
                    if (productIncome == null)
                    {
                        productIncome = 0;
                    }

                    var quantityCollection = from r in entities.Reports
                                             join p in entities.Products
                                             on r.ProductID equals p.ID
                                             where p.ID == productId
                                             select r.Quantity;

                    //ObjectResult<int?> quantityCollection = entities.usp_FindQuantity(product.ID);
                    //int? productQuantity = quantityCollection.FirstOrDefault();
                    decimal? productQuantity;
                    if (quantityCollection == null || quantityCollection.Count() == 0)
                    {
                        productQuantity = 0;
                    }
                    else
                    {
                        productQuantity = quantityCollection.Sum();
                    }

                    string jsonTemplate = String.Format(@"{{
  ""product-id"" : {0},
  ""product-name"" : ""{1}"",
  ""vendor-name"" : ""{2}"",
  ""total-quantity-sold"" : {3},
  ""total-incomes"" : {4},
}}", productId, productName, vendorName, productQuantity, productIncome);

                    resultJsons.Add(productId, jsonTemplate);

                    // JObject currentObject = JObject.Parse(jsonTemplate);
                    //
                    // jsonObjects.Add(currentObject);
                }
            }

            return resultJsons;
        }

        static void RecordInMongoDB(Dictionary<int, string> jsonList)
        {
            MongoClient mongoClient = new MongoClient("mongodb://localhost/");
            MongoServer mongoServer = mongoClient.GetServer();
            MongoDatabase db = mongoServer.GetDatabase("SupermarketDB");
            MongoCollection<BsonDocument> productCollection = db.GetCollection("Products");

            foreach (var json in jsonList)
            {
                BsonDocument doc = BsonDocument.Parse(json.Value);
                productCollection.Insert(BsonDocument.Parse(json.Value));
            }
        }

        static void RecordFiles(Dictionary<int, string> jsonList)
        {
            foreach (var json in jsonList)
            {
                using (FileStream fs = File.Open("../../Product-Reports/" + json.Key + ".json", FileMode.Create))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(json.Value);
                }
            }
        }
    }
}
